import { useEffect, useCallback } from 'react';

interface HotkeyBinding {
  key: string;
  callback: () => void;
}

export function useHotkeys(bindings: HotkeyBinding[]) {
  const handleKeyDown = useCallback((event: KeyboardEvent) => {
    for (const binding of bindings) {
      const [modifiers, key] = binding.key.split('+');
      const modifierKeys = modifiers ? modifiers.split('-') : [];

      const ctrlPressed = modifierKeys.includes('ctrl');
      const altPressed = modifierKeys.includes('alt');
      const shiftPressed = modifierKeys.includes('shift');
      const metaPressed = modifierKeys.includes('meta');

      if (
        event.ctrlKey === ctrlPressed &&
        event.altKey === altPressed &&
        event.shiftKey === shiftPressed &&
        event.metaKey === metaPressed &&
        event.key.toLowerCase() === key.toLowerCase()
      ) {
        event.preventDefault();
        binding.callback();
        break;
      }
    }
  }, [bindings]);

  useEffect(() => {
    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [handleKeyDown]);
}
